package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class TodayBestService {

    @Autowired
    private UserService userService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    public TodayBest findTodayBest() {
        //获取User对象，无需对User对象校验，其一定不为null
        User user = UserThreadLocal.get();
        //查询推荐用户（今日佳人）,通过登录用户的id查找
        TodayBest todayBest = recommendUserService.findTodayBest(user.getId());
        if (null == todayBest) {
            //如果查询结果为空,则给出默认的推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(80L);//固定值
        }
        //如果不为空则需要补全今日佳人的个人信息
        UserInfo userInfo = userInfoService.findUserInfo(todayBest.getId());
        if (null == userInfo) {
            return null;
        }
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setTags(userInfo.getTags().split(","));

        return todayBest;
    }

    /**
     * 查询推荐用户列表
     *
     * @param queryParam 这个参数是用户从前端页面传递过来的参数
     * @return
     */
    public PageResult findPageInfo(RecommendUserQueryParam queryParam) {
        //获取User对象，无需对User对象校验，其一定不为null
        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());
        //pageInfo中的records参数中的数据,是recommendUserService在调用方法时从mongodb中查询出的推荐用户集合
        // ,之后在封装在records中
        PageInfo<RecommendUser> pageInfo = recommendUserService.findPageInfo(user.getId(),
                queryParam.getPage(),
                queryParam.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            //没有查询到推荐的用户列表
            return pageResult;
        }
        //不为空则需要填充个人信息
        //收集推荐用户的id,使用Set集合保存
        Set<Long> userIds = new HashSet<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);

        /*if (queryParam.getGender() != null) {
            //选择条件性别
            queryWrapper.eq("sex", queryParam.getGender().equals("man") ? 1 : 2);
        }
        if(queryParam.getAge()!=null){
            //选择条件年龄小于等于对应的参数
            queryWrapper.le("age",queryParam.getAge());
        }
        if(queryParam.getCity()!=null){
            //选择条件为城市
            queryWrapper.eq("city",queryParam.getCity());
        }*/

        List<UserInfo> userInfoList = userInfoService.findPageInfo(queryWrapper);
        if (CollectionUtils.isEmpty(userInfoList)) {
            //没有查询到推荐用户信息
            return pageResult;
        }
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setTags(userInfo.getTags().split(","));
            //缘分值
            for (RecommendUser record : records) {
                if (record.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    todayBest.setFateValue(Double.valueOf(Math.floor(record.getScore())).longValue());
                    break;
                }
            }
            todayBests.add(todayBest);
        }
        //按照缘分值进行倒序排序
        Collections.sort(todayBests,
                (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());

        pageResult.setItems(todayBests);
        return pageResult;
    }
}
